<template>
  <uni-icons
    class="asset-scan"
    :class="{ 'active-color': isActive }"
    type="scan"
    :size="size"
    :color="iconColor"
    @click="handleClick"
  ></uni-icons>
</template>

<script setup>
import utils from '@/common/js/utils/index.js'; // 引入公共方法
const {
  Custom_sendLog, // 输出日志
  blurAllInputs, // 让所有input失去焦点
} = utils;

import { scanCodeAsset } from '@/api';
import { onMounted, ref, watch, computed } from 'vue';

const props = defineProps({
  size: {
    type: Number,
    default: 40,
  },
  color: {
    type: String,
    default: '#fff',
  },
  asset: {
    type: String,
    default: '',
  },
});

const emit = defineEmits(['scansuccess', 'clearscanres']);

const info = reactive({
  getEnvironmentType: '', // 获取运行环境
});

const clickCount = ref(0); // 点击次数
const isActive = ref(false); // 图标激活状态

// 根据 asset 值动态计算图标颜色
const iconColor = computed(() => {
  return props.asset ? '#FF0000' : props.color; // 如果 asset 有值，图标颜色变为红色
});

// 浏览器端扫码
const scan_2 = () => {
  // 浏览器端扫码逻辑
  console.log('浏览器端扫码');
};

// app上扫码
const scan_3 = () => {
  uni.scanCode({
    success: (res) => {
      sacn_callback(res.result);
    },
  });
};

// 扫码后的回调
const sacn_callback = (code) => {
  scanCodeAsset({
    assetCode: code,
  })
    .then((res) => {
      if (res.code === '0') {
        if (res.data.length) {
          emit('scansuccess', res.data);
        } else {
          uni.showToast({
            title: '未获取到该设备信息',
            icon: 'none',
          });
        }
      } else {
        uni.showToast({
          title: '获取信息失败',
          icon: 'none',
        });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: '扫码失败',
        icon: 'none',
      });
    });
};

// 处理点击事件
const handleClick = () => {
  clickCount.value++;
  if (clickCount.value === 1) {
    setTimeout(() => {
      if (clickCount.value === 1) {
        toSacn(); // 单击事件，执行扫码
      } else {
        emit('clearscanres'); // 双击事件，执行清空
      }
      clickCount.value = 0; // 重置点击次数
    }, 300); // 300ms 内判断是否为双击
  }
};

// 扫码逻辑
const toSacn = async () => {
  if (info.getEnvironmentType === 'window_plus_has') {
    // plus.webview 运行的环境
    blurAllInputs(); // 让所有input失去焦点

    // 隐藏键盘
    uni.hideKeyboard();
    await new Promise((resolve) => setTimeout(resolve, 50));

    uni.navigateTo({
      url: '/pages/only/PlusScan/PlusScan',
      events: {
        scansuccess: function (data) {
          Custom_sendLog({
            name: '资产扫码后的回调', // 名称
            data: data, // 输出的信息
          });

          const msg = data.msg || {};
          sacn_callback(msg.result || '');
        },
      },
    });
  } else if (info.getEnvironmentType === 'window_plus_no') {
    // 普通浏览器环境(h5)
    blurAllInputs(); // 让所有input失去焦点

    // 隐藏键盘
    uni.hideKeyboard();
    await new Promise((resolve) => setTimeout(resolve, 50));

    uni.showToast({
      title: '暂不支持扫码',
      icon: 'none',
    });
    scan_2();
  } else {
    // app环境
    scan_3();
  }
};

// 监听 asset 值的变化
watch(
  () => props.asset,
  (newVal) => {
    isActive.value = !!newVal; // 如果 asset 有值，激活状态
  }
);

onMounted(() => {
  info.getEnvironmentType = utils.getEnvironmentType(); // 获取运行环境
});
</script>

<style lang="scss" scoped>
.active-color {
  color: #ff0000; /* 激活状态下的颜色 */
}
</style>
